#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         PythonScript.py
#
# Copyright:    Copyright (c) 2005, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  A PythonScript is a simple Component that permits capturing
#               of text imformation during the process of an assessment.
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Component import Component, ComponentInfo
from Products.KnowledgeEngine.Assessible import Assessible
from Products.KnowledgeEngine.AssessmentComponentState import AssessmentComponentState
from Products.KnowledgeEngine.AssessmentComponentValueTypes import *
from Products.KnowledgeEngine.KERLExtensions import KERLExtensions
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *
from Products.KnowledgeEngine.KERFProcessor import *
from Products.KnowledgeEngine.KERLProcessor import InvalidKerlOperator

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## PythonScriptInfo Class Definition
class PythonScriptInfo(ComponentInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """

    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Return the class name
        """
        
        return 'PythonScript'

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Python Script"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "py"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/PythonScript_icon.gif', globals())

    #---------------------------------------------------------------#

    def isInstanceOf(self, className):
        """
            Returns if the class is an instance of the specified
            className, or implements the interface specified 
            by the className
        """

        return className == 'Assessible' or ComponentInfo.isInstanceOf(self, className)
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ComponentInfo.onConfigureProperties(self)
        
        #add the 'reportContent' property        
        self.addPropertyDefinition(PropertyDefinition(identity="reportContent", displayName="Report Content", description="Text to be displayed for this component when used in a report", defaultValue="", propertyType=pt_STRING, propertyFormat=pf_HTML, propertyStructure=ps_ATOMIC))        
        
        self.addPropertyDefinition(PropertyDefinition(
            identity="script", 
            displayName="Script", 
            description="The python script to execute", 
            defaultValue="", 
            propertyType=pt_STRING, propertyFormat=pf_TEXT_MULTILINE, propertyStructure=ps_ATOMIC
        ))
        
        
        #add the 'isVisible' property
        self.addPropertyDefinition(PropertyDefinition(identity="isVisible", displayName="Is Visible", description="Show the calculated value as a read only block", 
        defaultValue=0, propertyType=pt_BOOLEAN, propertyFormat=pf_CHECKBOX, propertyStructure=ps_ATOMIC))        
        
        self.addPropertyDefinition(PropertyDefinition(identity="dontRecalculate", displayName="Don't Recalculate", description="Don't recalculate the value on every assessment", 
        defaultValue=0, propertyType=pt_BOOLEAN, propertyFormat=pf_CHECKBOX, propertyStructure=ps_ATOMIC))         

    #---------------------------------------------------------------#

#####################################################################
## PythonScript Class Definition
class PythonScript(Component, Assessible, KERLExtensions):
    """
        Defines a simple component to represent one or more lines of 
        text entered during an assessment.
    """

    #---------------------------------------------------------------#

    #TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = PythonScriptInfo()
    
    #---------------------------------------------------------------#

    # DTML Methods
    index_html = DTMLFile('dtml/index_html', globals())
    simplereport_html = DTMLFile('dtml/simplereport_html', globals())
    
    dontRecalculate = false

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the PythonScript"        

        Component.__init__(self, id, identity)

    #---------------------------------------------------------------#

    def onAfterIdentityChange(self, identityMappings):
        """
            Handle Knowledge Engine specific actions after the 
            identity of this object has changed.
            
            The identityMappings dictionary holds 
            mappings from oldIdentities -> newIdentities
            (including this object)
                        
        """

        #perform default identity changes
        Component.onAfterIdentityChange(self, identityMappings)

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """

        #perform default onAfterInstanciation for the parent
        Component.onAfterInstanciation(self)
    
       
    #---------------------------------------------------------------#
    # BEGIN: Assessible Implementation                              #
    #---------------------------------------------------------------#
        
    def getAssessmentValueType(self):
        """
            ABSTRACT: Returns the type of the value that is to be stored
            for this component when it's assessment state is persisted.
            
            NOTE 1: See AssessmentComponentValueTypes for a list of defined contants       
            NOTE 2: This method MUST be overriden in the implementing
            class to specify the correct type for value persistence
            
            RETURN TYPE: String
        """
        
        #textbox assessment values are strings
        return st_STRING
        
    #---------------------------------------------------------------#
        
    def getDefaultValue(self):
        """
            Returns a blank default value
        """
                
        return None
        
    #---------------------------------------------------------------#                
    
    def getComponentProperty(self, identity, propertyName, assessment = None):
        """
            Returns the value of the specified property, given the
            identity of the component (which may be used to lookup states) and
            an assessment.

            RETURNS: None if the property doesn't exist
        """        
        print "***********"
        if propertyName == "value":
            v = assessment.getComponentState(identity).getValue()
            print "PythonScript::getComponentProperty for %s = %s" % (assessment.getIdentity(), `v`)
            return v
        else:
            return Component.getComponentProperty(self, identity, propertyName, assessment)        
    #---------------------------------------------------------------#        
    
    def getIsVisible(self):
        """
           Returns the isShown property
        """
        
        return self.isVisible
        
        
    #---------------------------------------------------------------#
        
    def getDefaultAssessmentState(self, assessment):
        """
            ABSTRACT: Constructs and returns a suitable 'default' 
            AssessmentComponentState for the provided Assessment
            instance.

            NOTE: This method MUST be overriden in the implementing
            class to provide a suitable default value for the component
            
            RETURN TYPE: AssessmentComponentState
        """
        
        return AssessmentComponentState(assessment.getIdentity(), assessment.getModelIdentity(), self.getIdentity(), self.getAssessmentValueType(), self.getDefaultValue(), revision=assessment.getRevision())
              
    
    #---------------------------------------------------------------#
    
    def getDontRecalculate(self):
        """ Returns True if the user has chosen 'Don't Recalculate' """
        
        return self.dontRecalculate
        
    
    #---------------------------------------------------------------#

    def executeScript(self, assessment):
        """ Executes the python script """
        
        import new
        
        script = self.script
        
        script = script.replace("\r\n","\n")
        
        context = self
        
        namespace = {'context': self, 
                     'user': context.REQUEST.AUTHENTICATED_USER,
                     'request': context.REQUEST,
                     'assessment': assessment,
                    }
                     
        
        exec script in namespace
        
        return namespace.get('RETURN')
        
        #code = compile(script,"None", 'exec')
        
        #namespace = {'context': self}
        
        #func = new.function( code, namespace )
        #result = func()
        
        #return `namespace`
        #return exec script in locals(), globals()


    #---------------------------------------------------------------#
    
    def updateAssessmentState(self, assessment, formValue):
        """
            ABSTRACT: Updates the specified assessment using
            the provided HTTP REQUEST formValue.
            
            NOTE: This method MUST be overriden in the implementing
            class to suitably update the component state
        """
            
        #get the current assessment state for the component from the assessment
        state = assessment.getComponentState(self.getIdentity())
        current = state.getValue()            
            
        if current and self.getDontRecalculate():
            return                
            
        value = self.executeScript(assessment)
            
        
        
        #update the current state
        state.setValue(value)
        
        # If a searchIndex is defined, add that info to the component state
        searchIndex = getattr(self, 'searchIndex', False)
        if searchIndex:
            state.setSearchIndex(searchIndex)
            state.setSearchValue(value)
        
        #update the assessment
        assessment.setIsModified(true)
            
    #---------------------------------------------------------------#
    # END: Assessible Implementation                                #
    #---------------------------------------------------------------#
    
    #---------------------------------------------------------------#
    # BEGIN: KERLExtensions Implementation                          #
    #---------------------------------------------------------------#

    def compileKERLtoJavaScript(self, expression):
        """
            Returns a Python string that represents a JavaScript
            expression, which may be used to evaluate the status
            of the component class specific KERL expression.

            NOTE: this method is primarily used to produce
            JavaScript expressions that form the basis of the
            client-side showif technology.
            
            RETURN TYPE: String         
        """
        
        #example: cond="['txt1','contains', value]" returns 'document.getElementById("txt1").value.indexOf(value)>=0'
        #example: cond="['txt1','doesntcontain', value]" returns 'document.getElementById("txt1").value.indexOf(value)<0'
        #example: cond="['txt1','equals', value]" returns 'document.getElementById("txt1").value==value'
        #example: cond="['txt1','notequal', value]" returns 'document.getElementById("txt1").value!=value'

        #get the identity (which is the identity of itself)        
        identity = self.getIdentity()

        #get the operator
        opr = expression[1]

        #get the value
        value = asJavaScript(expression[2])

        #determine the result
        result = "document.getElementById(\"" + identity + "\").value"
        
        if opr == "contains":
            return result + ".indexOf(\"" + value + "\")>=0"
        
        elif opr == "doesntcontain":
            return result + ".indexOf(\"" + value + "\")<0"
        
        elif opr == "equals":
            return result + "==\"" + value + "\""
        
        elif opr == "doesntequal":
            return result + "!=\"" + value + "\""
        
        else:
            raise InvalidKerlOperator, opr
            #return "true"

    #---------------------------------------------------------------#

    def compileKERLtoEnglish(self, expression):
        """
            Returns a string representing an 'English' version
            of the component class specific KERL expression.

            NOTE: this method is primarily used to produce
            English descriptions of KERL expressions that may be 
            used to describe things like AssessmentFilters
            
            RETURN TYPE: String         
        """
        
        return ""

    #---------------------------------------------------------------#

    def evaluate(self, expression, assessment):
        """
            Evalutes the component class specific KERL expression
            using the provided assessment.

            NOTE: this method is primarily used to produce
            JavaScript expressions that form the basis of the
            client-side showif technology.

            RETURN TYPE: Boolean         
        """
        
        #get the identity
        identity = self.getIdentity()

        #get the operator
        opr = expression[1]

        #get the value
        value = asJavaScript(expression[2])

        #get the stored state
        state = assessment.getComponentState(identity)

        #evaluate the expression
        if opr == "contains":
            return state.getValue().find(value) >= 0
        
        elif opr == "doesntcontain":
            return state.getValue().find(value) == -1
        
        elif opr == "equals":
            return state.getValue() == value
        
        elif opr == "doesntequal":
            return state.getValue() != value
        
        else:
            raise InvalidKerlOperator, opr
            #return true
    
    #---------------------------------------------------------------#

    def getDependencies(self, expression):
        """
            Returns a list of components that are required to
            evaluate the component class specific KERL expression.

            NOTE: Includes the specific component itself.

            RETURN TYPE: {Component} indexed by Component.getIdentity()
       """

        return {self.getIdentity():self}
    
    #---------------------------------------------------------------#

    def updateKERLIdentities(self, expression, identityMappings):
        """
            Returns the expression with the appropriate old identities
            (as identified by the identityMappings) replaced with 
            new identities.
        """
        
        #get the component identity from the expression (first element)
        identity = expression[0]
        
        #is the component in the identityMappings?
        if identityMappings.has_key(identity):
            expression[0] = identityMappings[identity]
        
        return expression

    #---------------------------------------------------------------#
    # END: KERLExtensions Implementation                            #
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Component Information with the Knowledge Engine
registerGenericObjectClass(PythonScript)

#####################################################################
